﻿using System;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Jobs;
using Unity.Profiling;
using UnityEngine;

namespace Tutorial6_InterlockedJob
{
    public unsafe class InterlockedMonoRun : MonoBehaviour
    {
        private NativeArray<long> inputData;
        private void Start()
        {
            inputData = new NativeArray<long>(100000, Allocator.Persistent);
            for (int i = 0; i < inputData.Length; i++)
            {
                inputData[i] = i;
            }
        }

        private ProfilerMarker _marker = new ProfilerMarker("InterlockedMonoRun");
        
        private void Update1()
        {
            _marker.Begin();
            long* sum = (long*)UnsafeUtility.Malloc(UnsafeUtility.SizeOf<long>(), UnsafeUtility.AlignOf<long>(), Allocator.TempJob);
            *sum = 0;
            var job = new InterlockedParallelJob()
            {
                inputData = inputData,
                outputSumData = sum
            };
                
            job.ScheduleParallel(inputData.Length, 256, new JobHandle()).Complete();
            Debug.Log("SUM : " + (*sum));
            
            UnsafeUtility.Free(sum, Allocator.TempJob);
            
            _marker.End();
        }

        private void OnDestroy()
        {
            inputData.Dispose();
        }
    }
}